package com.itheima.job;

import com.itheima.mapper.EmpMapper;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CleanImgJob {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;


    @Autowired
    private EmpMapper empMapper;

//    @Scheduled(cron = "0/10 * * * * ?")
    public void cleanOssImage() throws Exception {
        // 1.查询oss上所有的图片
        List<String> imgInOss = aliyunOSSOperator.list();
        imgInOss.forEach(System.out::println);

        // 2.查询员工表中所有的图片
        List<String> imgInDB = empMapper.selectAllImage();
        imgInDB = imgInDB.stream().map(img -> img.replaceAll("https://sz151-zzy.oss-cn-shenzhen.aliyuncs.com/", ""))
                .collect(Collectors.toList());
        imgInDB.forEach(System.out::println);

        // 3.oss-db,removeAll 从oss集合中删除image
        log.info("oss共有{}张，数据库中有{}张", imgInOss.size(), imgInDB.size());
        imgInOss.removeAll(imgInDB);

        log.info("需要删除的图片共有{}张", imgInOss.size());

        if (imgInOss.size() > 0) {
            // 调用oss删除
            aliyunOSSOperator.remove(imgInOss);
        }

    }
}
